/**
 * 
 */
package com.effectivsocial.security;

import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.effectivsocial.domain.Role;
import com.effectivsocial.domain.User;
import com.effectivsocial.service.api.UserService;


/**
 * @author Dhrubo
 *
 */
@Named
public class SimpleUserDetailsService implements UserDetailsService {
	
	private static final Logger logger = LoggerFactory.getLogger(SimpleUserDetailsService.class);
	
	@Inject
	private UserService userService;
	
	
	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@Override
	@Transactional(readOnly=true)
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		logger.debug("Retrieving user - {},",username);
		
		User user = null;
		SimpleUserDetails userDetails = null;
		try{
			user = userService.findByEmail(username);
			
			logger.debug("Retrieved user - {},",user);
			
			if(user == null) {
				throw new UsernameNotFoundException("Username -" + username + " not found in DB");
			}
			
			
			if(!user.isActivated())
				throw new UsernameNotFoundException("User with email - " + username + " is not activated.");
			
			List<GrantedAuthority> roles = new ArrayList<GrantedAuthority> ();
			
			List<Role> userRoles = new ArrayList<Role>(user.getRoles());
			
			for(Role role : userRoles) {
				roles.add(new SimpleGrantedAuthority(role.getName()));
			}
			
						
			logger.debug("###### User roles - {}", roles);
			
					
			userDetails = new SimpleUserDetails(user, roles);
			
			
		}
		catch(Exception er){
			
			logger.error("Error retrieving user - ", er);
			throw new UsernameNotFoundException("Error retrieving user - " + er.getMessage());
		}
		
		
		return userDetails;
	}

}
